﻿Imports System.ServiceModel.DomainServices.Client

Partial Public Class DetallGestioNotes
    Inherits ChildWindow

    Private _Nota As Web.Nota
    Public ReadOnly Property Nota As Web.Nota
        Get
            Return _Nota
        End Get
    End Property

    Private _Mode As EnumMode
    Public ReadOnly Property Mode As EnumMode
        Get
            Return _Mode
        End Get
    End Property

    Public Enum EnumMode
        ModeAlta
        ModeModificacio
    End Enum

#Region "Crear i Destruir"
    Public Sub New(pMode As EnumMode, pNota As Web.Nota)
        MyBase.New()

        InitializeComponent()
        _Mode = pMode
        _Nota = pNota
    End Sub


    Private Sub Child_Closed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Closed
        Application.Current.RootVisual.SetValue(Control.IsEnabledProperty, True)
    End Sub

    Private Sub DetallGestioNotes_Loaded(sender As Object, e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        If RiaContext.Current.Authentication.User.Identity.IsAuthenticated = True Then
            Me.Activity.IsActive = True

            AddHandler Contexte.UsuarisCarregats, AddressOf UsuarisCarregats
            Contexte.LoadUsuaris()

            AddHandler Contexte.HostalsCarregats, AddressOf HostalsCarregats
            Contexte.LoadHostals()

            If Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Administrador Then rdbTodos.IsEnabled = True

            If Mode = EnumMode.ModeAlta Then
                _Nota.Data = Date.SpecifyKind(Now.Date, DateTimeKind.Unspecified)
                _Nota.DataCaducitat = Date.SpecifyKind(Now.Date, DateTimeKind.Unspecified)
                _Nota.UsuariCreador = Contexte.UsuariActual
            Else
                Me.Title = StringLibrary.EditarNota

                If _Nota.IdUsuariDesti.HasValue Then
                    rdbUsuario.IsChecked = True
                ElseIf _Nota.IdHostalDesti.HasValue Then
                    rdbHostal.IsChecked = True
                Else
                    rdbTodos.IsChecked = True
                End If

            End If

            Me.gridDetall.DataContext = _Nota

        End If
    End Sub
#End Region

#Region "Carregar Dades"
    Private _HostalsCarregats As Boolean = False
    Private _UsuarisCarregats As Boolean = False

    Private Sub UsuarisCarregats(ByVal Resultat As Boolean, ByVal Missatge As String)
        RemoveHandler Contexte.UsuarisCarregats, AddressOf UsuarisCarregats

        _UsuarisCarregats = True

        If _HostalsCarregats And _UsuarisCarregats Then
            RefrescarCombos()
            Me.Activity.IsActive = False
        End If
    End Sub

    Public Sub HostalsCarregats(ByVal Resultat As Boolean, ByVal Missatge As String)
        RemoveHandler Contexte.HostalsCarregats, AddressOf HostalsCarregats

        _HostalsCarregats = True

        If _HostalsCarregats And _UsuarisCarregats Then
            RefrescarCombos()
            Me.Activity.IsActive = False
        End If
    End Sub

    Public Sub RefrescarCombos()
        Dim LListaUsuaris As List(Of Web.Usuari)
        If Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Administrador Then
            LListaUsuaris = (From U As LullabyFullDeCaixa.Web.Usuari In Contexte.Usuaris Where U.IdTipusUsuari <> EnumTipusUsuari.Neteja).ToList
        Else
            Dim LListaHostalsAssignats As List(Of Web.Hostal) = (From UH As Web.UsuariHostal In Contexte.UsuariActual.UsuariHostals Select UH.Hostal).ToList
            LListaUsuaris = (From UH As Web.UsuariHostal In Contexte.DomainContext.UsuariHostals Where LListaHostalsAssignats.Contains(UH.Hostal) And UH.Usuari.IdTipusUsuari <> EnumTipusUsuari.Neteja Select UH.Usuari).ToList
            LListaUsuaris.AddRange((From U As Web.Usuari In Contexte.Usuaris Where U.IdTipusUsuari = EnumTipusUsuari.Administrador))
        End If

        'LListaUsuaris.Add(New Web.Usuari() With {.Id = -1, .Nom = ""})
        cboUsuaris.ItemsSource = LListaUsuaris.Distinct.OrderBy(Function(f) f.Nom)


        Dim LListaHostals As List(Of Web.Hostal)
        If Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Administrador Then
            LListaHostals = (From H As Web.Hostal In Contexte.Hostals).ToList
        Else
            LListaHostals = Contexte.HostalsPerUsuariActual
        End If

        'LListaHostals.Add(New Web.Hostal() With {.Id = -1, .Nom = ""})
        Me.cboHostals.ItemsSource = LListaHostals.OrderBy(Function(f) f.Nom)

    End Sub

#End Region

#Region "Guardar i Cancelar"
    Private Sub OKButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        EliminarObjectErrors()

        If Contexte.DomainContext.EntityContainer.HasChanges Then
            If ValidarDades() And Validacio.Errors.Count = 0 Then
                LullabyFullDeCaixa.Contexte.DomainContext.SubmitChanges(AddressOf DomainContext_SubmittedChanges, Nothing)
                Activity.IsActive = True
            End If
        Else
            Me.DialogResult = True
        End If
    End Sub

    Private Function ValidarDades() As Boolean
        Dim Resultat As Boolean = True

        'Que hi hagi algun radio button apretat
        If Not rdbHostal.IsChecked AndAlso Not rdbTodos.IsChecked AndAlso Not rdbUsuario.IsChecked Then
            Me.Validacio.Errors.Add(New ValidationSummaryItem(StringLibrary.DebeSeleccionarUnTipoDestinatario))
            Resultat = False
        End If

        'Si radio button es hostal hi ha d'haver un hostal seleccionat
        If rdbHostal.IsChecked AndAlso cboHostals.SelectedItem Is Nothing Then
            Me.Validacio.Errors.Add(New ValidationSummaryItem(StringLibrary.DebeSeleccionarUnHostal))
            Resultat = False
        End If

        'Si radio button es usuari hi ha d'haver un usuari seleccionat
        If rdbUsuario.IsChecked AndAlso cboUsuaris.SelectedItem Is Nothing Then
            Me.Validacio.Errors.Add(New ValidationSummaryItem(StringLibrary.DebeSeleccionarUnUsuario))
            Resultat = False
        End If

        Return Resultat
    End Function

    Private Sub DomainContext_SubmittedChanges(ByVal s As SubmitOperation)
        Activity.IsActive = False

        If s.HasError Then
            App.ReportError(StringLibrary.ErrorGuardantDades)
            s.MarkErrorAsHandled()
        Else
            Me.DialogResult = True
        End If
    End Sub

    Private Sub CancelButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        If LullabyFullDeCaixa.Contexte.DomainContext.EntityContainer.HasChanges Then
            LullabyFullDeCaixa.Contexte.DomainContext.RejectChanges()
        End If

        Me.DialogResult = False
    End Sub

    Public Sub EliminarObjectErrors()
        Dim i As Long

        i = 0
        While i < Validacio.Errors.Count
            If Validacio.Errors(i).ItemType = ValidationSummaryItemType.ObjectError Then
                Validacio.Errors.RemoveAt(i)
            Else
                i = i + 1
            End If
        End While
    End Sub
#End Region

#Region "Radio Buttons"
    Private Sub rdbTodos_Checked(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles rdbTodos.Checked

    End Sub

    Private Sub rdbHostal_Checked(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles rdbHostal.Checked
        cboHostals.IsEnabled = True
    End Sub

    Private Sub rdbUsuario_Checked(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles rdbUsuario.Checked
        cboUsuaris.IsEnabled = True
    End Sub

    Private Sub rdbTodos_UnChecked(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles rdbTodos.Unchecked

    End Sub

    Private Sub rdbHostal_UnChecked(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles rdbHostal.Unchecked
        _Nota.Hostal = Nothing
        cboHostals.IsEnabled = False
    End Sub

    Private Sub rdbUsuario_UnChecked(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles rdbUsuario.Unchecked
        _Nota.UsuariDesti = Nothing
        cboUsuaris.IsEnabled = False
    End Sub
#End Region

End Class
